package com.stox.client.ui.javafx.chartingy.event.listener;

import javafx.geometry.Point2D;
import javafx.scene.input.MouseEvent;

import com.stox.client.ui.javafx.chartingy.model.chart.Chart;
import com.stox.client.ui.javafx.chartingy.model.shape.TrendSegment;
import com.stox.client.ui.javafx.chartingy.view.ChartingView;
import com.stox.shared.core.model.intf.Callback;

public class TrendSegmentMouseEventStrategy implements ChartingMouseEventStrategy {

	private Callback<Void, Void> completionCallback;
	private TrendSegment trendSegment;

	@Override
	public void handle(final MouseEvent event) {
		if (MouseEvent.MOUSE_PRESSED.equals(event.getEventType())) {
			final ChartingView chartingView = (ChartingView) event.getSource();
			final Chart<?, ?> chart = chartingView.resolveChart(event.getSceneX(), event.getSceneY());
			if (null != chart) {
				trendSegment = new TrendSegment(chart, event.getSceneX(), event.getSceneY());
				chart.addShape(trendSegment);
				event.consume();
			}
		} else if (MouseEvent.MOUSE_DRAGGED.equals(event.getEventType())) {
			if (null != trendSegment) {
				final Chart<?, ?> chart = trendSegment.getChart();
				final Point2D point = chart.getChartContentArea().sceneToLocal(event.getSceneX(), event.getSceneY());
				trendSegment.getEnd().setCenterX(point.getX());
				trendSegment.getEnd().setCenterY(point.getY());
				event.consume();
			}
		} else if (MouseEvent.MOUSE_RELEASED.equals(event.getEventType())) {
			completionCallback.execute(null);
			event.consume();
		}
	}

	@Override
	public void attach(final ChartingView chartingView) {
		chartingView.addEventFilter(MouseEvent.MOUSE_PRESSED, this);
		chartingView.addEventFilter(MouseEvent.MOUSE_DRAGGED, this);
		chartingView.addEventFilter(MouseEvent.MOUSE_RELEASED, this);
	}

	@Override
	public void detach(final ChartingView chartingView) {
		chartingView.removeEventFilter(MouseEvent.MOUSE_PRESSED, this);
		chartingView.removeEventFilter(MouseEvent.MOUSE_DRAGGED, this);
		chartingView.removeEventFilter(MouseEvent.MOUSE_RELEASED, this);
	}

	@Override
	public void setCompletionCallback(final Callback<Void, Void> completionCallbak) {
		completionCallback = completionCallbak;
	}


}
